var app = require('../app');
var debug = require('debug')(app.NAME);
var _ = require('lodash');

var K = require('../common/common');

var m = {
  USER_IN_SESSION: 'k_user',
  CAPTCHA_IN_SESSION: 'k_captcha',
  PERMISSIONS_IN_USER: 'k_permissions',
  instance: function (_request) {
    var hRequest = K.object('RequestHelper');
    hRequest.isLogIn = function () {
      return _request.session && _request.session[m.USER_IN_SESSION];
    };
    hRequest.logIn = function (user) {
      var permissions = [];
      var roles = user.get('roles');
      for (var i in roles) {
        permissions = _.union(permissions, roles[i].get('permissions'));
      }
      user.set(m.PERMISSIONS_IN_USER, permissions);
      _request.session[m.USER_IN_SESSION] = user;
    };

    hRequest.loginUser = function () {
      return _request.session[m.USER_IN_SESSION];
    };
    hRequest.userPermissions = function () {
      if (! hRequest.isLogIn()) {
        return [];
      }
      return hRequest.loginUser()[m.PERMISSIONS_IN_USER];
    };

    hRequest.logOut = function () {
      if (_request.session) {
        _request.session[m.USER_IN_SESSION] = null;
      }
    }

    return hRequest;
  }
}

module.exports = m;